﻿// Created by:  Tomer Shamam
// Date:        06-Feb-2009
// From:        http://blogs.microsoft.co.il/blogs/tomershamam/archive/2007/10/30/wpf-localization-on-the-fly-language-selection.aspx

using System;
using System.Globalization;
using System.Threading;
using System.ComponentModel;
using ScrumTable.Common;

namespace ScrumTable.UI.View.Localization
{
    public sealed class LanguageContext : INotifyPropertyChanged
    {
        #region Fields

        public static readonly LanguageContext Instance = new LanguageContext();

        private CultureInfo _cultureInfo;
        private LanguageDictionary _dictionary; 

        #endregion

        #region Properties

        public CultureInfo Culture
        {
            get
            {
                if (_cultureInfo == null)
                {
                    _cultureInfo = CultureInfo.CurrentUICulture;
                }
                return _cultureInfo;
            }
            set
            {
                PreCondition.AssertNotNull(value, "value");

                if (value == _cultureInfo)
                {
                    return;
                }
                if (_cultureInfo != null)
                {
                    LanguageDictionary currentDictionary = LanguageDictionary.GetDictionary(_cultureInfo);
                    currentDictionary.Unload();
                }
                _cultureInfo = value;
                LanguageDictionary newDictionary = LanguageDictionary.GetDictionary(_cultureInfo);
                Thread.CurrentThread.CurrentUICulture = _cultureInfo;
                newDictionary.Load();
                Dictionary = newDictionary;
                OnPropertyChanged("Culture");
            }
        }

        /// <summary>
        /// Sets the Culture based on a culture string (de-CH, en-Us....)
        /// </summary>
        public string CultureString
        {
            set
            {
                Culture = CultureInfo.GetCultureInfo(value);
            }
        }

        public LanguageDictionary Dictionary
        {
            get { return _dictionary; }
            set
            {
                if (value != null && value != _dictionary)
                {
                    _dictionary = value;
                    OnPropertyChanged("Dictionary");
                }
            }
        }
 
        #endregion

        #region Initialization

        private LanguageContext() { } 

        #endregion

        #region INotifyPropertyChanged Members

        private void OnPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
		
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}